Lesson 7 - loops

While loops will only loop if the conditional expression is true. The conditions follow the exact same rules as if statements., This means you can use comparision operators and logical operators. The example below will allow a player to guess numbers until they have won. the condition is "not gameWon" or "gameWon == false".


gameWon = False
secret = 21
# keep going while the game has not been won
while not gameWon:
    guess = input("Enter a number ")
    # see if they were close or not!
    diff = guess - secret
    # diff could be negative!
    if diff < 0:
        diff = diff * -1
    # ensure that guess is within 20
    if guess > secret and diff <= 20:
            print "guess is too big"
    elif guess < secret and diff <=20:
            print "guess is too small"
    elif guess == secret:
            print "Well done you guessed correctly!"
            gameWon = True
    else:
      print "Your nowhere near!"


Like if statements it is important to watch the indentation. Anything which is to be repeated must be indented. Notice as well that the if statements true and false blocks are indented further (twice). This is not only good programming practice but it is how python knows what statements are inside itteration and selection. The code can be further adapted to allow lives to be considered. The final version of the game can be downloaded here (secretv3.py) and also can be seen below.


import random

gameWon = False
secret = random.randrange(1,100)
lives = 5
# keep going while the game has not been won
while not gameWon and lives >0:
    guess = input("Enter a number ")
    # see if they were close or not!
    diff = guess - secret
    # diff could be negative!
    if diff < 0:
        diff = diff * -1
    # ensure that guess is within 20
    if guess > secret and diff <= 20:
            print "guess is too big"
    elif guess < secret and diff <=20:
            print "guess is too small"
    elif guess == secret:
            print "Well done you guessed correctly!"
            gameWon = True
    else:
      print "Your nowhere near!"
    lives = lives -1
    print "you have ", str(lives), " left"

# has the game been won?
if(not gameWon):
    print "You have lost. Bow your head in shame! The number was ", secret


The loop will end if the game has been won or the user has run out of lives. Each loop the number of lives is reduced by one thus ensuring the loop will end. The other addition to the code is a random number generator. The exact syntax of this will be looked at in more advanced lessons. However it is fairly obvious how it works so feel free to use it. Do not forget the import random!

For loops syntax will be covered in deatail in the advanced part of this course.

key learning points